<template>
  <div class="home" ref="home">
    <div class="top">
    	<span v-if="search_show">速音</span>
    	<img src="../assets/img/search.png" @click="search" v-if="search_show"/>
      <transition name="slide-fade">
          <div class="pos" v-if="posShow">
          	<img src="../assets/img/previous2.png" @click="prev" class="prev"/>
          	<input type="text" placeholder="请输入关键字..." placeholder-style="color:#ddd" v-model="input" @keydown="ok" ref="input" >
          	<ul v-if="showName.length!=0">
              <li v-for="item in showName" @click="preview(item)">{{item}}</li>
            </ul>

            <span class="btn" @click="search_btn">搜索</span>
          </div>
      </transition>

    </div>
    <van-swipe :autoplay="5000">
      <van-swipe-item v-for="(image, index) in images" :key="index">
        <img v-lazy="image" />
      </van-swipe-item>
    </van-swipe>
    <list msg="Welcome to Your Vue.js App"  :listData="listData" @reflesh="getData"/>
    <div class="mar"></div>
    <div class="bot" @click="bot">
        <div class="cover">
          <div v-if="$store.state.list.length>0">
            <img :src="$store.state.list[$store.state.musicIndex].img" alt="" class="xuan">
            <div class="info2">
              <span>{{$store.state.list[$store.state.musicIndex].title}}</span>
              <span>{{$store.state.list[$store.state.musicIndex].author}}</span>
            </div>
            <img :src="$store.state.play?require('../assets/img/About/over.png'):require('../assets/img/About/open.png')" class="play" @click.stop="changeClick"/>
          </div>
          <div v-else-if="$store.state.list.length<=0" class="noMusic">
            无播放音乐
          </div>
          <img src="../assets/img/menu.png" alt="" class="menu" @click.stop="show=!show">
        </div>
    </div>
    <van-popup
      v-model="show"
      close-icon="close"
      position="bottom"
      :style="{ height: '30%' }"
      round
    >
    <ul class="popup">
      <div><img src="../assets/img/del.png" alt="" class="del" @click="del"></div>
      <li v-for="(item,index) in $store.state.list" @click="popupLiClick(item.hash,index,item.album_id)" v-if="$store.state.list.length>0">
        <div class="tit_aut">
          <span :class="$store.state.bof==item.hash?'on2':''">{{item.title}}</span>
          <span :class="$store.state.bof==item.hash?'on2':'no2'" >- {{item.author}}</span>
        </div>
          <span class="x" @click.stop="x(index)">x</span>
      </li>
      <li v-if="$store.state.list.length<=0" class="popup_no">播放列表为空</li>
    </ul>
    </van-popup>
  </div>
</template>

<script>
// @ is an alias to /src
import list from '../components/list/list.vue';
import { get, post } from '../../utils/request.js';

export default {
  name: 'Home',
  data() {
    return {
      // input
      input: '',
      search_show: true,
      posShow: false,

      // list
      listData: [],
      // swiper
      images: [
        require('../assets/img/banner1.jpg'),
        require('../assets/img/banner2.jpg'),
        require('../assets/img/banner3.jpg'),
      ],
      show: false, // 弹出层,
      showName: [],
      album_id: null,
    };
  },
  methods: {
    preview(item) {
      this.$refs.input.focus();
      this.input = item;
    },
    // 播放、暂停
    changeClick() {
      const audio = document.querySelector('audio');
      const xuan = document.querySelector('.xuan');// 左下角的旋转图片
      const store = this.$store.state;
      store.play = !store.play;
      if (store.play) {
        audio.play();
        xuan.style.animationPlayState = 'running';
      } else {
        audio.pause();
        xuan.style.animationPlayState = 'paused';
      }
    },

    // 播放列表选中播放
    popupLiClick(hash, index, album_id) {
      this.album_id = album_id;
      const store = this.$store.state;
      const audio = document.querySelector('audio');
      if (store.list[index].src == '') {
        this.$toast.fail('播放失败');// vant组件提示失败
        return;
      }
      if (hash != store.list[store.musicIndex].hash) {
        store.musicIndex = index;
        audio.load();
        audio.play();
        store.play = true;
      }
      this.show = false;
      store.bof = hash;
    },
    getData(n = this.Inv) {
      if (n == 0) {
        this.one();
      } else if (n == 1) {
        this.qingqiu('time2', 'list2', 'http://mobilecdnbj.kugou.com/api/v3/rank/newsong?version=9108&plat=0&with_cover=1&pagesize=100&type=1&area_code=1&page=1&with_res_tag=1');
      } else if (n == 2) {
        this.qingqiu('time3', 'list3', 'http://mobilecdnbj.kugou.com/api/v3/rank/newsong?version=9108&plat=0&with_cover=1&pagesize=100&type=2&area_code=1&page=1&with_res_tag=1');
      }
    },
    // 删除播放列表
    del() {
      const store = this.$store.state;
      const audio = document.querySelector('audio');
      this.$dialog.confirm({
        // title: '提示',
        message: '确定要清空播放列表？',
      })
        .then(() => {
          audio.pause();
          this.show = false;
          store.musicIndex = 0;
          store.m = 0;// 下一首初始化歌词盒子的translateY移动
          store.action = 0;// 初始化索引
          store.move = 0;
          store.list.splice(0, store.list.length);
          store.bof = null;// 这是list的绿色播放图标状态
          const xuan = document.querySelector('.xuan');// 左下角的旋转图片
          xuan.style.animationPlayState = 'paused';
        })
        .catch(() => {

        });
    },
    // 播放列表的x
    x(index) {
      const audio = document.querySelector('audio');
      const store = this.$store.state;
      if (index == store.musicIndex) {
        audio.pause();
      }
      store.musicIndex--;
      store.list.splice(index, 1);
      if (store.list.length == 0) {
        audio.pause();
        this.show = false;
        store.musicIndex = 0;
        store.m = 0;// 下一首初始化歌词盒子的translateY移动
        store.action = 0;// 初始化索引
        store.move = 0;
        store.list.splice(0, store.list.length);
        store.bof = null;// 这是list的绿色播放图标状态
        const xuan = document.querySelector('.xuan');// 左下角的旋转图片
        xuan.style.animationPlayState = 'paused';
      }
    },
    bot() {
      if (this.$store.state.list.length > 0) {
        const { hash } = this.$store.state.list[this.$store.state.musicIndex];
        const { album_id } = this;
        this.$router.push({
          name: 'About',
          query: {
            hash,
            album_id,
          },
        });
      }
    },
    search_btn() {
      this.$router.push({
        name: 'Search',
        query: {
          keyword: this.input,
        },
      });
    },
    // 按下手机键盘搜索键
    ok(e) {
      if (e.keyCode == 13) {
        this.$router.push({
          name: 'Search',
          query: {
            keyword: this.input,
          },
        });
      }
    },
    search() {
    	this.search_show = false;// 搜索的图标隐藏
      // this.toumingdu=1;//显示搜索盒子
      this.posShow = true;
      setTimeout(() => {
        this.$refs.input.focus();
      }, 500);
    },
    prev() {
    	this.search_show = true;
      this.showName = [];
      this.posShow = false;
    },
    /*
     * 将秒转换为 分:秒
    */
    s_to_hs(s) {
      let h;
      h = Math.floor(s / 60);
      s %= 60;
      h += '';
      s += '';
      h = (h.length == 1) ? `0${h}` : h;
      s = (s.length == 1) ? `0${s}` : s;
      return `${h}:${s}`;
    },
    // watch监听Inv的函数
    qingqiu(time, list, url) {
      if (this.getlocal(time) == null) {
        const obj1 = {
         	expires: 1000 * 60 * 60 * 24 * 3,
         	startTime: new Date().getTime(),
         	name: 'time',
         	value: 'guoqi',
        };
        this.listData = [];
        const sendDate = (new Date()).getTime();
        post(url, {}).then((res) => {
          let demo = {};
          const arr1 = [];
          const data = JSON.parse(res.data.replace(/<!--KG_TAG_RES_START-->/g, '').replace(/<!--KG_TAG_RES_END-->/g, '')).data.info;
          data.forEach((item) => {
            const duration = this.s_to_hs(item.duration);
            demo = {
              filename: item.filename, duration, hash: item.hash, album_id: item.album_id,
            };
            arr1.push(demo);
          });
          this.listData = this.split_array(arr1, 15);

          localStorage.setItem(list, JSON.stringify(this.listData));
          localStorage.setItem(time, JSON.stringify(obj1));
          const receiveDate = (new Date()).getTime();
          if (list == 'list2') {
            this.$store.state.responseTimeMs2 = receiveDate - sendDate;
          }
          if (list == 'list3') {
            this.$store.state.responseTimeMs3 = receiveDate - sendDate;
          }
        });
      }
    },
    // 获取localStorage,并验证过期时间
    getlocal(name) {
      if (localStorage.getItem(name) != null) {
        const item = JSON.parse(localStorage.getItem(name));
        const timedate = new Date().getTime();
        if (timedate - item.startTime < item.expires) {
          return item.value;
        }
        localStorage.removeItem(name);
        return null;
      }
      return null;
    },
    split_array(arr, len) {
      const a_len = arr.length;
      const result = [];
      for (let i = 0; i < a_len; i += len) {
        result.push(arr.slice(i, i + len));
      }
      return result;
    },
    async one() {
      if (this.$store.state.Inv == 0) {
        if (this.getlocal('time1') == null) {
          // 设置过期的存储参数，当前是3天时间
          const obj1 = {
            expires: 1000 * 60 * 60 * 24 * 3,
            startTime: new Date().getTime(),
            name: 'time',
            value: 'guoqi',
          };
          this.listData = [];
          const res = await post('http://mobilecdnbj.kugou.com/api/v5/special/recommend?recommend_expire=0&sign=52186982747e1404d426fa3f2a1e8ee4&plat=0&uid=0&version=9108&page=1&area_code=1&appid=1005&mid=286974383886022203545511837994020015101&_t=1545746286', {});
          let demo = {};
          const arr1 = [];
          res.data.data.list.forEach((item) => {
            item.songs.forEach((item2) => {
              const duration = this.s_to_hs(item2.duration);
              demo = {
                filename: item2.filename, duration, hash: item2.hash, album_id: item2.album_id,
              };
              arr1.push(demo);
            });
          });
          this.listData = this.split_array(arr1, 15);
          localStorage.setItem('list1', JSON.stringify(this.listData));
          localStorage.setItem('time1', JSON.stringify(obj1));
        }
      }
    },
  },
  components: {
    list,
  },
  mounted() {
    this.$refs.home.style.height = `${document.documentElement.clientHeight}px`;
    if (this.$store.state.list.length > 0) {
      const xuan = document.querySelector('.xuan');// 左下角的旋转图片
      if (document.querySelector('audio').paused) {
        xuan.style.animationPlayState = 'paused';
      } else {
        xuan.style.animationPlayState = 'running';
      }
    }
  },
  async created() {
    this.one();
  },
  computed: {
    Inv() {
      return this.$store.state.Inv;
    },
  },
  watch: {
    Inv(n, o) {
      this.getData(n);
    },
    input(n, o) {
      this.showName = [];
      if (n != o && n != '') {
        post(`http://mobilecdn.kugou.com/api/v3/search/song?format=json&keyword=${n}&page=${1}&pagesize=10`, {}).then((res) => {
          if (res.data.data.info.length == 0) {
            return;
          }
          res.data.data.info.forEach((item) => {
            this.showName.push(item.songname);
          });
        });
      }
    },
  },

};
</script>
<style lang="scss">
  // top动画 start
  // .slide-fade-leave-active 用于 2.1.8 以下版本 */
  .slide-fade-enter-active {
    transition: all .8s ease;
  }
  .slide-fade-leave-active {
    transition: all .8s cubic-bezier(1.0, 0.5, 0.8, 1.0);
  }
  .slide-fade-enter, .slide-fade-leave-to
   {
    transform: translateY(10px);
    opacity: 0;
  }
  // top动画 end
  .home{
    background-color: #f2f2f2;
    height:100%;
  }
  .top{
  	position: relative;
  	background-color: #2b9939;
  	text-align: center;
  	color: white;
  	height: 80px;
  	line-height: 80px;
  	span:nth-child(1){
  		margin-left: 55px;
      font-size: 33px;
      font-weight: 550;
      letter-spacing: 10px;
  	}
  	img{
  		width: 35px;
  		height: 35px;
      margin-top: 25px;
      margin-right: 25px;
  		float: right;
  	}
  	.pos{
  		width: 100%;
  		background-color:#2b9939;
  		position: absolute;
  		bottom: 0;
  		left: 0;
  		display: flex;
  		justify-content: center;//x轴排列
  		align-items: center;//y轴排列
      height:80px;
      transition:all 0.5s;
  		input{
  			background: none;
  			border: 1px solid #fff;
  			font-size: 25px;
  			width: 50%;
  			height: 50px;
  			border-radius: 7px;
  			text-align: left;
  			text-indent: 0.65em;
        outline: none;
        color: #fff;
      }
      input::placeholder{
        color: #ddd;
      }
      ul{
        background-color: #fff;
        color: #555;
        position: absolute;
        height: auto;
        width: 51%;
        height: 340px;
        z-index: 3;
        top: 70px;
        left: 23.5%;
        text-align: left;
        text-indent: 20px;
        line-height: 55px;
        font-size: 25px;
        overflow: auto;
      }
      ul>li{
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
  		.btn{
  			font-size: 25px;
  			border: 1px solid #fff;
  			border-radius: 7px;
  			margin-left: 0;
  			padding: 0 12px;
  			height: 53px;
  			line-height: 53px;
  		}
  		.prev{
  			width: 35px;
  			height: 35px;
        margin-bottom: 30px;
  		}

  	}
  }
  // 轮播
  .van-swipe{
      height: 325px;
  }
   .van-swipe-item img{
     width: 100%;
     height: 100%;
     display: block;
   }
   .mar{
     height: 85px;
   }
   //底部悬浮
   .bot{
     position: fixed;
     bottom: 0;left: 0;width: 100%;height: 90px;background-color: rgba(0,0,0,0.6);
     .cover{
       img.xuan{
        width: 80px;
        height: 80px;border-radius: 50%;margin: 5px 0 0 10px;
        display: block;
        animation-name: go;
        animation-duration: 5s;
        animation-timing-function: linear;
        animation-iteration-count:infinite;
        animation-play-state:paused;
        float: left;
      }
      img.menu{
        width: 40px;
        height: auto;
        position: absolute;
        right: 5%;
        top: 50%;
        transform: translateY(-50%);
      }
      .play{
        width: 40px;
        height: auto;
        position: absolute;
        right: 14%;
        top: 50%;
        transform: translateY(-50%);
      }
      .info2{
        width: 80%;
        height: 90px;
        float: left;
        display: flex;
        flex-direction: column;
        color: #fff;
        font-size: 28px;
        line-height: 45px;
        margin-left: 5%;
        span{
          flex: 1;
        }
        span:nth-child(1){
          width: 80%;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        span:nth-child(2){
          font-size: 23px;
          width: 80%;
          color:#dcdcdc;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }
     }
     @keyframes  go{
     	from{
     		transform: rotate(0deg);
     	}
     	to{
     		transform: rotate(360deg);
     	}
     }
   }

   .popup{
     div{
       height: 50px;

       .del{
         width: 40px;
         float: right;
         margin-top: 10px;
         margin-right: 3.2%;
       }
     }

     li{
       height: 80px;
       line-height: 80px;
       width: 90%;
       margin: 0 auto;
       position: relative;
       div.tit_aut{
         width: 80%;
         height: 100%;
         overflow: hidden;
         text-overflow:ellipsis;
         white-space: nowrap;
         display: inline-block;
       }
       span{
         font-size: 30px;

       }
       span:nth-child(2){
         font-size: 20px;
         padding-left: 10px;

       }
       span.no2{
         color: #777;
       }
       span.x{
         position: absolute;
         right: 0;
         top:0;
         color: #aaa;
         font-size: 20px;
       }
     }
   }
   .on2{
     color: red;
   }
    .noMusic{
      color: #FFF;
      font-size: 28px;
      line-height: 85px;
      padding-left: 50px;
    }
    .popup_no{
      text-align: center;
      font-size: 25px;
      color: #666;
    }
</style>
